/**
 * 简化版短信验证码监听器
 * 适合初学者使用的版本
 * 支持将验证码发送到服务端
 */

// 请求短信权限和网络权限
runtime.requestPermissions(["android.permission.READ_SMS", "android.permission.RECEIVE_SMS", "android.permission.INTERNET"]);

/**
 * 提取验证码的函数
 * @param {string} text - 短信内容
 * @returns {string} - 验证码
 */
function getCode(text) {
    // 匹配4-6位数字验证码
    let match = text.match(/\d{4,6}/);
    return match ? match[0] : null;
}

/**
 * 发送验证码到服务端
 * @param {string} code - 验证码
 * @param {string} sender - 发送方号码
 * @param {string} content - 完整短信内容
 */
function sendCodeToServer(code, sender, content) {
    try {
        let data = {
            code: code,
            sender: sender || "unknown",
            content: content,
            timestamp: new Date().toISOString(),
            device: device.getAndroidId()
        };
        
        console.log("正在发送验证码到服务端...");
        
        let response = http.postJson("http://192.168.1.54:8000/sms", data);
        
        if (response.statusCode == 200) {
            console.log("验证码发送成功:", response.body.string());
            toast("验证码已发送到服务端");
        } else {
            console.log("发送失败，状态码:", response.statusCode);
            toast("发送失败: " + response.statusCode);
        }
    } catch (error) {
        console.error("发送验证码失败:", error);
        toast("网络错误，发送失败");
    }
}

/**
 * 获取最新短信
 * @returns {object} - 包含短信内容和发送方的对象
 */
function getLatestSMS() {
    try {
        let uri = "content://sms/inbox";
        let cursor = context.getContentResolver().query(
            android.net.Uri.parse(uri),
            ["body", "date", "address"],
            null, null, "date DESC"
        );
        
        if (cursor && cursor.moveToFirst()) {
            let body = cursor.getString(0);
            let address = cursor.getString(2);
            cursor.close();
            return {
                content: body,
                sender: address
            };
        }
        return null;
    } catch (e) {
        console.log("读取短信失败:", e);
        return null;
    }
}

// 主程序
console.log("开始监听短信验证码...");
toast("短信监听启动");

let lastSMS = "";

// 每2秒检查一次新短信
let timer = setInterval(() => {
    let smsData = getLatestSMS();
    
    if (smsData && smsData.content !== lastSMS) {
        lastSMS = smsData.content;
        console.log("收到短信:", smsData.content);
        console.log("发送方:", smsData.sender);
        
        // 提取验证码
        let code = getCode(smsData.content);
        
        if (code) {
            console.log("验证码:", code);
            toast("验证码: " + code);
            
            // 发送到服务端
            sendCodeToServer(code, smsData.sender, smsData.content);
            
            // 复制到剪贴板
            setClip(code);
            toast("验证码已复制: " + code);
            
            // 尝试自动填充到输入框
            let input = className("EditText").findOne(1000);
            if (input) {
                input.setText(code);
                toast("验证码已自动填充");
            }
        }
    }
}, 2000);

// 按返回键停止
events.observeKey();
events.onKeyDown("back", () => {
    clearInterval(timer);
    toast("监听已停止");
    exit();
});

console.log("按返回键停止监听");